<template>
    <div class="space-sidebar">
        <div class="filter-header">
            <el-button type="primary" size="small" @click="handleCreateSpace">
                创建空间
            </el-button>
            <el-button type="primary" size="small" @click="handleCreateGroup">
                创建空间组
            </el-button>
        </div>

        <el-scrollbar>
            <div class="space-list">
                <!-- 空间组列表 -->
                <div v-if="spaceGroups.length > 0" class="space-group-section">
                    <div v-for="group in spaceGroups" :key="group.id" class="space-group-item">
                        <div class="group-header">
                            <div class="group-name" @click="handleGroupSelect(group)">
                                {{ group.name }}
                            </div>
                            <el-dropdown trigger="click">
                                <el-icon class="more-icon">
                                    <More />
                                </el-icon>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item @click="handleEditGroupName(group)">重命名</el-dropdown-item>
                                        <el-dropdown-item @click="handleDeleteGroup(group)">删除</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>
                        <div class="group-spaces">
                            <div v-for="space in group.spaces" :key="space.id" class="space-tag"
                                :class="{ active: selectedSpace?.id === space.id }" @click="handleSpaceSelect(space)">
                                <span>{{ space.name }}</span>
                                <el-dropdown trigger="click">
                                    <el-icon class="more-icon">
                                        <More />
                                    </el-icon>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item @click="handleEditSpaceName(space)">重命名</el-dropdown-item>
                                            <el-dropdown-item @click="handleDeleteSpace(space)">删除</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 未分组空间列表 -->
                <div class="space-section">
                    <div class="section-title">未分组空间</div>
                    <div v-for="space in ungroupedSpaces" :key="space.id" class="space-item"
                        :class="{ active: selectedSpace?.id === space.id }" @click="handleSpaceSelect(space)">
                        <span>{{ space.name }}</span>
                        <el-dropdown trigger="click">
                            <el-icon class="more-icon">
                                <More />
                            </el-icon>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item @click="handleEditSpaceName(space)">重命名</el-dropdown-item>
                                    <el-dropdown-item @click="handleDeleteSpace(space)">删除</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </div>
            </div>
        </el-scrollbar>

        <!-- 创建空间弹窗 -->
        <el-dialog v-model="spaceDialogVisible" :title="isEditingSpace ? '编辑空间' : '创建空间'" width="30%"
            :close-on-click-modal="false">
            <el-form :model="spaceForm" label-width="80px">
                <el-form-item label="空间名称" required>
                    <el-input v-model="spaceForm.name" placeholder="请输入空间名称" />
                </el-form-item>
                <el-form-item label="所属分组">
                    <el-select v-model="spaceForm.groupId" placeholder="请选择空间组" clearable style="width: 100%">
                        <el-option v-for="group in spaceGroups" :key="group.id" :label="group.name" :value="group.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="spaceDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleConfirmSpace">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 创建空间组弹窗 -->
        <el-dialog v-model="groupDialogVisible" :title="isEditingGroup ? '编辑空间组' : '创建空间组'" width="30%"
            :close-on-click-modal="false">
            <el-form :model="groupForm" label-width="80px">
                <el-form-item label="组名称" required>
                    <el-input v-model="groupForm.name" placeholder="请输入空间组名称" />
                </el-form-item>
                <el-form-item label="选择空间">
                    <el-checkbox-group v-model="groupForm.selectedSpaces">
                        <div class="space-checkbox-list">
                            <el-checkbox v-for="space in spaces" :key="space.id" :label="space.id">
                                {{ space.name }}
                            </el-checkbox>
                        </div>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="groupDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleConfirmGroup">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 重命名弹窗 -->
        <el-dialog v-model="renameDialogVisible" :title="renameType === 'group' ? '重命名空间组' : '重命名空间'" width="30%"
            :close-on-click-modal="false">
            <el-form :model="renameForm" label-width="80px">
                <el-form-item label="名称" required>
                    <el-input v-model="renameForm.name"
                        :placeholder="renameType === 'group' ? '请输入空间组名称' : '请输入空间名称'" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="renameDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleConfirmRename">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { More } from '@element-plus/icons-vue'
// 定义props
const props = defineProps({
    selectedSpace: {
        type: Object,
        required: true
    }
})

// 定义事件
const emit = defineEmits(['space-change'])

// 空间组列表
const spaceGroups = ref([
    {
        id: 'teaching_building',
        name: '教学楼',
        spaces: []
    },
    {
        id: 'admin_building',
        name: '行政楼',
        spaces: []
    }
])

// 空间列表
const spaces = ref([
    {
        id: 'room2',
        name: '教学楼2层',
        groupId: 'teaching_building',
    },
    {
        id: 'room3',
        name: '教学楼3层',
        groupId: 'teaching_building',
    }
])

// 计算未分组的空间
const ungroupedSpaces = computed(() => {
    return spaces.value.filter(space => !space.groupId)
})

// 弹窗相关
const spaceDialogVisible = ref(false)
const groupDialogVisible = ref(false)
const renameDialogVisible = ref(false)
const isEditingSpace = ref(false)
const isEditingGroup = ref(false)
const renameType = ref('')  // 'space' or 'group'

// 表单数据
const spaceForm = ref({
    id: '',
    name: '',
    groupId: '',
    devices: []
})

const groupForm = ref({
    id: '',
    name: '',
    selectedSpaces: [] // 存储选中的空间ID数组
})

const renameForm = ref({
    id: '',
    name: ''
})

// 初始化空间组的空间列表
const initGroupSpaces = () => {
    spaceGroups.value.forEach(group => {
        group.spaces = spaces.value.filter(space => space.groupId === group.id)
    })
}
initGroupSpaces()

// 处理创建空间
const handleCreateSpace = () => {
    isEditingSpace.value = false
    spaceForm.value = {
        id: '',
        name: '',
        groupId: '',
        devices: []
    }
    spaceDialogVisible.value = true
}

// 处理空间选择
const handleSpaceSelect = (space) => {
    emit('space-change', space)
}

// 处理创建空间组
const handleCreateGroup = () => {
    isEditingGroup.value = false
    groupForm.value = {
        id: '',
        name: '',
        selectedSpaces: []
    }
    groupDialogVisible.value = true
}

// 处理空间组选择
const handleGroupSelect = (group) => {
    // 可以添加空间组选择的逻辑
}

// 确认创建/编辑空间组
const handleConfirmGroup = () => {
    if (!groupForm.value.name) {
        ElMessage.warning('请输入空间组名称')
        return
    }

    if (isEditingGroup.value) {
        // 更新现有空间组
        const index = spaceGroups.value.findIndex(item => item.id === groupForm.value.id)
        if (index !== -1) {
            spaceGroups.value[index].name = groupForm.value.name

            // 更新空间的组关系
            spaces.value.forEach(space => {
                if (groupForm.value.selectedSpaces.includes(space.id)) {
                    space.groupId = groupForm.value.id
                } else if (space.groupId === groupForm.value.id) {
                    space.groupId = ''
                }
            })
        }
        ElMessage.success('更新成功')
    } else {
        // 创建新空间组
        const newGroup = {
            id: Date.now().toString(),
            name: groupForm.value.name,
            spaces: []
        }
        spaceGroups.value.push(newGroup)

        // 更新选中空间的组关系
        spaces.value.forEach(space => {
            if (groupForm.value.selectedSpaces.includes(space.id)) {
                space.groupId = newGroup.id
            }
        })

        ElMessage.success('创建成功')
    }

    groupDialogVisible.value = false
    initGroupSpaces()
}

// 确认创建/编辑空间
const handleConfirmSpace = () => {
    if (!spaceForm.value.name) {
        ElMessage.warning('请输入空间名称')
        return
    }

    if (isEditingSpace.value) {
        // 更新现有空间
        const index = spaces.value.findIndex(item => item.id === spaceForm.value.id)
        if (index !== -1) {
            spaces.value[index] = { ...spaces.value[index], ...spaceForm.value }
        }
        ElMessage.success('更新成功')
    } else {
        // 创建新空间
        const newSpace = {
            ...spaceForm.value,
            id: Date.now().toString(),
            devices: []
        }
        spaces.value.push(newSpace)
        ElMessage.success('创建成功')
    }

    spaceDialogVisible.value = false
    initGroupSpaces()
}

// 处理重命名空间组
const handleEditGroupName = (group) => {
    renameType.value = 'group'
    renameForm.value = {
        id: group.id,
        name: group.name
    }
    renameDialogVisible.value = true
}

// 处理重命名空间
const handleEditSpaceName = (space) => {
    renameType.value = 'space'
    renameForm.value = {
        id: space.id,
        name: space.name
    }
    renameDialogVisible.value = true
}

// 确认重命名
const handleConfirmRename = () => {
    if (!renameForm.value.name) {
        ElMessage.warning('请输入名称')
        return
    }

    if (renameType.value === 'group') {
        const group = spaceGroups.value.find(item => item.id === renameForm.value.id)
        if (group) {
            group.name = renameForm.value.name
        }
    } else {
        const space = spaces.value.find(item => item.id === renameForm.value.id)
        if (space) {
            space.name = renameForm.value.name
        }
        initGroupSpaces()
    }

    ElMessage.success('重命名成功')
    renameDialogVisible.value = false
}

// 处理删除空间组
const handleDeleteGroup = (group) => {
    ElMessageBox.confirm(
        '确认删除该空间组？组内空间将被移至未分组空间',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 将组内空间移至未分组
        spaces.value.forEach(space => {
            if (space.groupId === group.id) {
                space.groupId = ''
            }
        })

        // 删除空间组
        const index = spaceGroups.value.findIndex(item => item.id === group.id)
        if (index !== -1) {
            spaceGroups.value.splice(index, 1)
        }

        initGroupSpaces()
        ElMessage.success('删除成功')
    })
}

// 处理删除空间
const handleDeleteSpace = (space) => {
    ElMessageBox.confirm(
        '确认删除该空间？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        const index = spaces.value.findIndex(item => item.id === space.id)
        if (index !== -1) {
            spaces.value.splice(index, 1)
        }
        initGroupSpaces()
        ElMessage.success('删除成功')
    })
}
</script>

<style lang="scss" scoped>
.space-sidebar {
    width: 240px;
    height: 100%;
    background-color: #fff;
    border-radius: var(--border-radius-base);
    display: flex;
    flex-direction: column;

    .filter-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
            font-weight: 500;
            color: var(--color-text-primary);
            font-size: 14px;
        }

        .button-group {
            display: flex;
            gap: 8px;
        }
    }

    .space-list {
        padding: 16px 0;

        .space-group-section {
            margin-bottom: 16px;

            .space-group-item {
                padding: 12px;
                border: 1px solid var(--el-border-color);
                border-radius: 4px;
                margin-bottom: 8px;

                .group-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 8px;

                    .group-name {
                        font-weight: 500;
                        cursor: pointer;

                        &:hover {
                            color: var(--el-color-primary);
                        }
                    }

                    .more-icon {
                        cursor: pointer;
                        padding: 4px;

                        &:hover {
                            background-color: var(--el-fill-color-light);
                        }
                    }
                }

                .group-spaces {
                    display: flex;
                    flex-direction: column;
                    gap: 4px;
                    padding-left: 12px;

                    .space-tag {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        padding: 4px 8px;
                        border-radius: 4px;
                        cursor: pointer;
                        font-size: 12px;

                        &:hover {
                            background-color: var(--el-fill-color-light);
                        }

                        &.active {
                            color: var(--el-color-primary);
                            background-color: var(--el-color-primary-light-9);
                        }

                        .more-icon {
                            opacity: 0;
                            padding: 2px;
                            border-radius: 2px;

                            &:hover {
                                background-color: var(--el-color-primary-light-8);
                            }
                        }

                        &:hover .more-icon {
                            opacity: 1;
                        }
                    }
                }
            }
        }

        .space-section {
            .section-title {
                font-size: 12px;
                color: var(--el-text-color-secondary);
                margin-bottom: 8px;
            }

            .space-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 32px;
                padding: 0 8px;
                border-radius: 4px;
                cursor: pointer;

                &:hover {
                    background-color: var(--el-fill-color-light);
                }

                &.active {
                    color: var(--el-color-primary);
                    background-color: var(--el-color-primary-light-9);
                }

                .more-icon {
                    opacity: 0;
                    padding: 4px;
                    border-radius: 4px;

                    &:hover {
                        background-color: var(--el-color-primary-light-8);
                    }
                }

                &:hover .more-icon {
                    opacity: 1;
                }
            }
        }
    }
}

.el-scrollbar {
    flex: 1;
    height: 0;
}

:deep(.el-dialog) {
    .el-form-item {
        margin-bottom: 20px;
    }
}

.space-checkbox-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
    max-height: 200px;
    overflow-y: auto;
    padding: 8px;
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
}
</style>